package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import control.Checker;
import dao.DAOException;
import dao.HostManager;
import dao.OSManager;
import dao.ProcessorManager;
import dao.hostexception.HostAlreadyExistException;
import entites.Host;

/**
 * Servlet type de gestions des stations
 * 
 * @author Josselyn Hermitte
 * @author Yanis Lisima
 *
 */
public class GestionDesServeurs extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String GET= "get";
	private static final String POST= "post";
	private static final String DO_LIST= "/list";
	private static final String DO_EDIT= "/edit";
	private static final String DO_DELETE= "/delete";
	private static final String DO_VALIDATE= "/validate";
	
	// paramètres d'instance
	private String urlErreurs= null;
	private ArrayList<String> erreursInitialisation= new ArrayList<String>();
	private String[] parametres= {"urlHostList","urlHostEdit","urlErreurs"};
	private Map<String, String> params= new HashMap<String, String>();
	
	//DAO
	HostManager hosts= null;
	OSManager osm= null;
	ProcessorManager pm= null;
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GestionDesServeurs() {
        super();
        
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init() throws ServletException {
		// Paramètres d'initialisation de la servlet
		ServletConfig config= getServletConfig();
		
		// Traitement des autres paramètres
		String valeur= null;
		for(int i=0;i<parametres.length;i++){
			valeur=config.getInitParameter(parametres[i]);
			if(valeur == null){
				erreursInitialisation.add("Le paramètre ["+parametres[i]+"] n'a pas été initialisé");
			}else {
				params.put(parametres[i], valeur);
			}
		}
		urlErreurs= config.getInitParameter("urlErreurs");
		if(urlErreurs==null){
			throw new ServletException(
					"Le paramètre [urlErreurs] n'a pas été initialisé");
		}
		Context context= null;
		try {
			context = new InitialContext();
			hosts= (HostManager) context.lookup("HostManagerBean/remote");
			osm= (OSManager) context.lookup("OSManagerBean/remote");
			pm= (ProcessorManager) context.lookup("ProcessorManagerBean/remote");
		} catch (NamingException e) {
			throw new ServletException(e);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//vérification de l'initialisation
		if(erreursInitialisation.size() != 0){
			request.setAttribute("erreurs", erreursInitialisation);
			getServletContext().getRequestDispatcher(urlErreurs).forward(request, response);
			return;
		}
		String methode= request.getMethod().toLowerCase();
		String action= request.getPathInfo();
		if(action == null){
			action= DO_LIST;
		}
		if(methode.equals(GET) && action.equals(DO_LIST)){
			// Liste des utilisateurs
			doListHosts(request, response);
			return;
		}
		if(methode.equals(GET) && action.equals(DO_DELETE)){
			// Suppression d'un utilisateur
			doDeleteHost(request, response);
			return;
		}
		if(methode.equals(GET) && action.equals(DO_EDIT)){
			// présentation du formulaire d'ajout/modification
			doEditHost(request, response);
			return;
		}
		if(methode.equals(POST) && action.equals(DO_VALIDATE)){
			// validation du formulaire d'ajout/modification
			doValidate(request, response);
			return;
		}
			// autres cas
		doListHosts(request, response);
	}

	/**
	 * Affiche la liste des utilisateurs
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void doListHosts(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		request.setAttribute("hosts", hosts.getAllHosts());
		getServletContext()
			.getRequestDispatcher(
					params.get("urlHostList")).forward(request, response);
	}
	
	/**
	 * Ajoute/modifie un utilisateur
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void doEditHost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		String hostname= request.getParameter("hostname");
		Host host=null;
		if(hostname != null){
			hosts.getHost(hostname);
		}
		if(host==null){
			host= new Host(hostname);
		}
		request.setAttribute("erreurEdit", "");
		request.setAttribute("hostname", host.getHostname());
		request.setAttribute("addresse", host.getAddresse());
		request.setAttribute("system", host.getSystem());
		request.setAttribute("processor", host.getProcessor());
		getServletContext().getRequestDispatcher(
				params.get("urlHostEdit")).forward(request, response);
	}
	
	/**
	 * Supprime un utilisateur
	 * @throws IOException 
	 */
	private void doDeleteHost(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String hostname= request.getParameter("hostname");
		hosts.delHost(hostname);
		response.sendRedirect("list");
	}
	/**
	 * validation d'Ajoute/modifie un utilisateur
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void doValidate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		boolean formErrone= false;
		String hostname= request.getParameter("hostname");
		if(hostname.trim().isEmpty()){
			request.setAttribute("erreurHostame", "Le nom est obligatoire");
			formErrone= true;
		}else if(!Checker.checkLogin(hostname)){
			request.setAttribute("erreurHostname", "nom invalide");
		}
		String addresse= request.getParameter("addresse");
		//int systemid= Integer.parseInt(request.getParameter("systemid"));
		//int procid= Integer.parseInt(request.getParameter("procid"));
		if(formErrone){
			showFormulaire(request, response,"");
			return;
		}
		Host host= new Host(hostname);
		host.setAddresse(addresse);
		try{
			try{
				hosts.addHost(host);
			}catch (HostAlreadyExistException e) {
				host= hosts.getHost(hostname); 
				host.setAddresse(addresse);
				hosts.updateHost(host);
			}
			//host.setSystem(osm.getOS(systemid));
			//host.setProcessor(pm.getProcessor(procid));
			//hosts.updateHost(host);
		}catch (DAOException e1) {
			
			showFormulaire(request, response, e1.getMessage());
			return;
		}
		response.sendRedirect("list");
	}
	
	private void showFormulaire(HttpServletRequest request,
			HttpServletResponse response, String erreurEdit) 
			throws ServletException, IOException {
		request.setAttribute("erreurEdit", erreurEdit);
		request.setAttribute("hostname", request.getParameter("hostname"));
		request.setAttribute("adresse", request.getParameter("addresse"));
		//request.setAttribute("systemid", request.getParameter("systemid"));
		//request.setAttribute("procid", request.getParameter("procid"));
		getServletContext().getRequestDispatcher(
				params.get("urlHostEdit")).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
